<template>
  <div :class="getWrapClass" class="tabsWrapDiv">
    <div class="tabsDiv">
      <div
        class="tabsItem"
        :class="item.isCheck ? 'active' : ''"
        v-for="(item, index) in tabsList"
        @click="checkTabs(index)"
        :key="index"
      >
        <div class="tabsItemContent">
          <div class="tabName">{{ item.name }}</div>
          <div class="close-btn" @click.stop="closeTabs(index)">
            <img src="../../../assets/images/closeTable.png" alt="" />
          </div>
        </div>
        <div class="left-round"></div>
        <div class="right-round"></div>
      </div>
    </div>
    <div style="width: 100%; height: 20px; background: rgb(242, 243, 244)"></div>
    <div
      v-if="
        [
          '商品供应商寻源',
          '供应商名单',
          // '历史评分',
          '评分列表',
          '风险扫描',
          '监控动态',
          '企业监控列表',
          '企业报告',
          '监控模型配置',
          '内部采购价格库',
          '商品价格寻源',
          '监理采购价格库',
          '新增采购价格库'
        ].includes(pageName)
      "
      style="width: 100%; padding: 0 27px 0 21px; box-sizing: border-box"
    >
      <PageTitle :goBack="false" :title="pageName" :border="false" />
    </div>
    <!--    <Tabs-->
    <!--      type="editable-card"-->
    <!--      size="small"-->
    <!--      :animated="false"-->
    <!--      :hideAdd="true"-->
    <!--      :tabBarGutter="3"-->
    <!--      :activeKey="activeKeyRef"-->
    <!--      @change="handleChange"-->
    <!--      @edit="handleEdit"-->
    <!--    >-->
    <!--      <template v-for="item in getTabsState" :key="item.query ? item.fullPath : item.path">-->
    <!--        <TabPane :closable="!(item && item.meta && item.meta.affix)">-->
    <!--          <template #tab>-->
    <!--            <TabContent :tabItem="item" />-->
    <!--          </template>-->
    <!--        </TabPane>-->
    <!--      </template>-->

    <!--      <template #rightExtra v-if="getShowRedo || getShowQuick">-->
    <!--&lt;!&ndash;        <TabRedo v-if="getShowRedo" />&ndash;&gt;-->
    <!--&lt;!&ndash;        <FoldButton v-if="getShowFold" />&ndash;&gt;-->
    <!--      </template>-->
    <!--    </Tabs>-->
  </div>
</template>
<script lang="ts">
  import type { RouteLocationNormalized, RouteMeta } from 'vue-router';

  import { defineComponent, computed, unref, ref, watch } from 'vue';
  import { Tabs } from 'ant-design-vue';
  import TabContent from './components/TabContent.vue';
  import FoldButton from './components/FoldButton.vue';
  import TabRedo from './components/TabRedo.vue';

  import { useGo } from '/@/hooks/web/usePage';

  import { useMultipleTabStore } from '/@/store/modules/multipleTab';
  import { useUserStore } from '/@/store/modules/user';

  import { initAffixTabs, useTabsDrag } from './useMultipleTabs';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useMultipleTabSetting } from '/@/hooks/setting/useMultipleTabSetting';

  import { REDIRECT_NAME } from '/@/router/constant';
  import { listenerRouteChange } from '/@/logics/mitt/routeChange';

  import { useRouter, useRoute } from 'vue-router';
  import PageTitle from '/@/components/PageTitle/index.vue';
  export default defineComponent({
    name: 'MultipleTabs',
    components: {
      PageTitle,
      TabRedo,
      FoldButton,
      Tabs,
      TabPane: Tabs.TabPane,
      TabContent,
    },
    setup() {
      const route = useRoute();
      let pageName = ref('');
      let tabsList = ref([]);
      pageName.value = route.meta.title;
      tabsList.value = localStorage.getItem('tabsList')
        ? JSON.parse(localStorage.getItem('tabsList'))
        : [];
      watch(
        () => route.fullPath,
        (newPath, oldPath) => {
          pageName.value = route.meta.title;
          if (tabsList.value.filter((item) => item.name === route.meta.title).length) {
            tabsList.value.forEach((item: any) => {
              if (item.name === route.meta.title) {
                item.isCheck = true;
              } else {
                item.isCheck = false;
              }
            });
          } else {
            tabsList.value.map((item) => {
              item.isCheck = false;
            });
            if (tabsList.value.length >= 8) {
              tabsList.value.splice(0, 1);
            }
            tabsList.value.push({
              name: route.meta.title,
              path: route.fullPath,
              isCheck: true,
            });
          }
          localStorage.setItem('tabsList', JSON.stringify(tabsList.value));
        },
      );
      const closeTabs = (index) => {
        if (!tabsList.value[index].isCheck) {
          tabsList.value.splice(index, 1);
          return;
        }
        tabsList.value.splice(index, 1);
        let tabItem = {};
        if (index) {
          tabItem = tabsList.value[index - 1];
          tabItem.isCheck = true;
          tabsList.value.splice(index - 1, 1, tabItem);
        } else {
          tabItem = tabsList.value[0];
          tabItem.isCheck = true;
          tabsList.value.splice(index - 1, 1, tabItem);
        }
        localStorage.setItem('tabsList', JSON.stringify(tabsList.value));
        router.push(tabItem.path);
      };
      const checkTabs = (index: number) => {
        tabsList.value.map((item) => {
          item.isCheck = false;
        });
        let tabItem = tabsList.value[index];
        tabItem.isCheck = true;
        tabsList.value.splice(index, 1, tabItem);
        router.push(tabItem.path);
        localStorage.setItem('tabsList', JSON.stringify(tabsList.value));
      };
      const affixTextList = initAffixTabs();
      const activeKeyRef = ref('');

      useTabsDrag(affixTextList);
      const tabStore = useMultipleTabStore();
      const userStore = useUserStore();
      const router = useRouter();

      const { prefixCls } = useDesign('multiple-tabs');
      const go = useGo();
      const { getShowQuick, getShowRedo, getShowFold } = useMultipleTabSetting();

      const getTabsState = computed(() => {
        return tabStore.getTabList.filter((item) => !item.meta?.hideTab);
      });

      const unClose = computed(() => unref(getTabsState).length === 1);

      const getWrapClass = computed(() => {
        return [
          prefixCls,
          {
            [`${prefixCls}--hide-close`]: unref(unClose),
          },
        ];
      });

      listenerRouteChange((route) => {
        const { name } = route;
        if (name === REDIRECT_NAME || !route || !userStore.getToken) {
          return;
        }

        const { path, fullPath, meta = {} } = route;
        const { currentActiveMenu, hideTab } = meta as RouteMeta;
        const isHide = !hideTab ? null : currentActiveMenu;
        const p = isHide || fullPath || path;
        if (activeKeyRef.value !== p) {
          activeKeyRef.value = p as string;
        }

        if (isHide) {
          const findParentRoute = router
            .getRoutes()
            .find((item) => item.path === currentActiveMenu);

          findParentRoute && tabStore.addTab(findParentRoute as unknown as RouteLocationNormalized);
        } else {
          tabStore.addTab(unref(route));
        }
      });

      function handleChange(activeKey: any) {
        activeKeyRef.value = activeKey;
        go(activeKey, false);
      }

      // Close the current tab
      function handleEdit(targetKey: string) {
        // Added operation to hide, currently only use delete operation
        if (unref(unClose)) {
          return;
        }

        tabStore.closeTabByKey(targetKey, router);
      }
      return {
        getWrapClass,
        handleEdit,
        handleChange,
        activeKeyRef,
        getTabsState,
        getShowQuick,
        getShowRedo,
        getShowFold,
        tabsList,
        closeTabs,
        checkTabs,
        pageName,
      };
    },
  });
</script>
<style lang="less">
  @import './index.less';
  .tabsWrapDiv {
    height: 44px;
    border-bottom: none;
  }
  .tabsDiv {
    display: flex;
    width: 100%;
    padding: 0px 24px;
    height: 44px;
    box-sizing: border-box;

    .tabsItem {
      width: 140px;
      height: 36px;
      border-radius: 8px 8px 0px 0px;
      text-align: left;
      line-height: 36px;
      background: #fff;
      margin-top: 8px;
      margin-right: 12px;
      position: relative;
      cursor: pointer;
      display: flex;
      align-items: center;

      .tabsItemContent {
        width: 100%;
        height: 28px;
        position: relative;
        box-sizing: border-box;
        padding: 0px 8px;
      }

      .tabName {
        width: calc(100% - 25px);
        height: 28px;
        line-height: 28px;
        font-size: 12px;
        font-weight: normal;
        color: #909399;
        white-space: nowrap; /* 确保文本在一行内显示 */
        overflow: hidden; /* 超出部分隐藏 */
        text-overflow: ellipsis; /* 使用省略号表示被截断的文本 */
      }
      .close-btn {
        position: absolute;
        width: 16px;
        height: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        right: 8px;
        top: 5px;
        display: none;
        cursor: pointer;
        border-radius: 50%;
        background: #eee;
      }

      .left-round {
        background: #f2f3f5;
        position: absolute;
        top: 0px;
        left: -12px;
        width: 12px;
        height: 36px;
        display: none;

        &::before {
          display: block;
          content: '';
          width: 12px;
          height: 36px;
          position: absolute;
          top: 0px;
          left: 0px;
          background: #fff;
          border-bottom-right-radius: 6px;
        }
      }

      .right-round {
        background: #f2f3f5;
        position: absolute;
        top: 0px;
        right: -12px;
        width: 12px;
        height: 36px;
        display: none;

        &::before {
          display: block;
          content: '';
          width: 12px;
          height: 36px;
          position: absolute;
          top: 0px;
          left: 0px;
          background: #fff;
          border-bottom-left-radius: 6px;
        }
      }
    }
    .tabsItem:hover {
      .tabsItemContent {
        background: #f2f3f5;
        border-radius: 4px;
      }

      .tabName {
        color: #303133;
      }

      .close-btn {
        display: block;
      }
    }
    .tabsItem.active {
      background: #f2f3f5;

      .tabName {
        color: #303133;
      }

      .left-round,
      .right-round {
        display: block;
      }
    }
  }
</style>
